<script setup lang="ts">
import { ref, onMounted } from 'vue'
import QRCode from 'qrcode.vue'
import { Edit } from '@element-plus/icons-vue'
import Map from '@arcgis/core/Map'
import MapView from '@arcgis/core/views/MapView'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import Graphic from '@arcgis/core/Graphic'
import GraphicsLayer from '@arcgis/core/layers/GraphicsLayer.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import Sketch from '@arcgis/core/widgets/Sketch.js'
import { useUserStore } from '@/stores'
import { jwtDecode } from 'jwt-decode'
import type { JwtPayload, layer } from '@/types/public'
import { addCourseAttendance, getCourseList } from '@/api/teacher'
import { baseURL } from '@/utils/request'
import gaodeLayer from '@/utils/GaoDeBaseLayer'

const mapViewContainer = ref<HTMLDivElement>()
const QRdialogVisible = ref(false)
const qrCodeUrl = ref('')
const AddCourseAttendanceBtn = ref(true)
const createMode = ref<'draw' | 'select'>('draw') // 默认绘图模式
let selectHandler: IHandle | null = null

// 添加课程选择相关的响应式变量
const courseDialogVisible = ref(false)
const selectedCourse = ref('')
const courseList = (await getCourseList()).data
// 初始化 FeatureLayer
const AttendanceFeature = new FeatureLayer({
  url: 'https://services8.arcgis.com/CmXfu09loK81if9H/arcgis/rest/services/AttendanceLayer/FeatureServer/0',
  outFields: ['*'],
})

const map = new Map({
  basemap: {
    baseLayers: [gaodeLayer],
  },
})
map.add(AttendanceFeature)

const view = new MapView({
  map,
  center: [116.7963581069489, 36.53729500053177],
  zoom: 15,
})

//添加选择课程对话框;
const confirmCourseSelection = async () => {
  courseDialogVisible.value = false
  if (createMode.value === 'draw') {
    // 选择课程后，开始绘制签到区域
    ElMessage.info('请在地图上绘制签到区域')
    //先创建出画图组件
    const sketch = new Sketch({
      view: view,
      layer: sketchLayer,
      visible: false,
    })
    //使用画图工具，画出一个签到活动范围
    sketch.create('polygon', { mode: 'click' })
    sketch.on('create', async function (event) {
      if (event.state === 'complete') {
        //获取教师信息
        const userStore = useUserStore()
        const decode = jwtDecode<JwtPayload>(userStore.token)
        const userName = decode['http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name']
        // 创建签到layer提交请求
        const attributes: layer = {}
        attributes['TeacherName'] = userName
        const result = await AttendanceFeature.applyEdits({
          addFeatures: [
            new Graphic({
              geometry: event.graphic.geometry,
              attributes,
            }),
          ],
        })
        console.log(result.addFeatureResults[0].objectId)
        sketch.layer.removeAll()
        sketch.cancel()

        // TODO: 发送API请求至后端，获取二维码URL
        const backResult = (
          await addCourseAttendance(result.addFeatureResults[0].objectId, selectedCourse.value)
        ).data
        console.log(backResult)
        // TODO:生成二维码
        qrCodeUrl.value = baseURL + 'Student/SignIn?attendanceId=' + backResult
        QRdialogVisible.value = true
        // 恢复按钮状态
        AddCourseAttendanceBtn.value = true
      }
    })
  } else {
    ElMessage.info('请选择签到区域')
    selectHandler = view.on('click', async (event) => {
      const results = (await view.hitTest(event)).results as __esri.MapViewGraphicHit[]
      const graphic = results.find((res) => res.graphic?.layer === AttendanceFeature)?.graphic

      if (graphic) {
        // 显示确认对话框
        ElMessageBox.confirm('确认使用该区域进行签到？', '提示')
          .then(async () => {
            const backResult = (
              await addCourseAttendance(graphic.attributes.OBJECTID, selectedCourse.value)
            ).data

            qrCodeUrl.value = `${baseURL}Student/SignIn?attendanceId=${backResult}`
            QRdialogVisible.value = true
            AddCourseAttendanceBtn.value = true
          })
          .finally(() => {
            selectHandler?.remove()
          })
      }
    })
  }
}

const cancelCourseAttendance = async () => {
  courseDialogVisible.value = false
  AddCourseAttendanceBtn.value = true
}

//创建出一个临时的图层 用于绘制sKetch图层
const sketchLayer = new GraphicsLayer()
map.add(sketchLayer)
// 创建签到
const createAttendance = async () => {
  courseDialogVisible.value = true
  AddCourseAttendanceBtn.value = false
}

onMounted(async () => {
  view.container = mapViewContainer.value!
  view.ui.add('CreateAttendanceBtn', 'top-right')
})
</script>

<template>
  <div ref="mapViewContainer" class="mapViewContainer">
    <el-button
      v-show="AddCourseAttendanceBtn"
      type="primary"
      :icon="Edit"
      id="CreateAttendanceBtn"
      @click="createAttendance"
    >
      创建签到
    </el-button>
  </div>

  <!-- 添加课程选择对话框 -->
  <el-dialog v-model="courseDialogVisible" title="选择课程" width="300px" center>
    <el-form>
      <el-form-item label="课程">
        <el-select v-model="selectedCourse" placeholder="请选择课程">
          <el-option
            v-for="(course, index) in courseList"
            :key="index"
            :label="course.courseName"
            :value="course.courseName"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建方式">
        <el-radio-group v-model="createMode">
          <el-radio label="draw">绘制新区域</el-radio>
          <el-radio label="select">选择现有区域</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="cancelCourseAttendance">取消</el-button>
        <el-button type="primary" @click="confirmCourseSelection"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog v-model="QRdialogVisible" title="签到二维码" width="300px" center>
    <div class="qr-container">
      <QRCode
        :value="qrCodeUrl"
        :options="{
          width: 200,
          margin: 0,
        }"
      />
    </div>
  </el-dialog>
</template>

<style scoped>
.mapViewContainer {
  width: 100%;
  height: 100%;
  position: relative;
}

.qr-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}
</style>
